<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Controller;

/**
 * Description of BrandController
 *
 * @author qingf
 */
class GoodsController extends \Think\Controller
{

    /**
     * @var \Admin\Model\GoodsModel
     */
    private $_model = null;

    protected function _initialize()
    {
        $this->_model = D('Goods');
    }

    public function index()
    {
        //获取品牌列表
        $this->assign($this->_model->getList());
        $this->display();
    }

    public function add()
    {
        if (IS_POST) {
            //收集数据
            if ($this->_model->create() === false) {
                $this->error(get_error($this->_model));
            }
            /*var_dump(I('post.'));
            exit;*/
            if ($this->_model->addGoods() === false) {
                $this->error(get_error($this->_model));
            }
            $this->success('添加成功', U('index'));
        } else {
            $this->before_view();
            $this->display();
        }
    }

    public function edit($id)
    {
        if (IS_POST) {
            //收集数据
            if ($this->_model->create() === false) {
                $this->error(get_error($this->_model));
            }
            if ($this->_model->saveGoods($id) === false) {
                $this->error(get_error($this->_model));
            }
            $this->success('修改成功', U('index'));
        } else {
            //展示数据
            $row = $this->_model->findGoods($id);
            $this->assign('row', $row);
            //获取所有的分类
            $this->before_view();
            $this->display('add');
        }
    }

    public function remove($id)
    {
        if ($this->_model->deleteCategory($id) === false) {
            $this->error(get_error($this->_model));
        } else {
            $this->success('删除成功', U('index'));
        }
    }

    private function before_view()
    {
        $goods_arr = $this->_model->getGoodsInfo();
        $categories = $goods_arr['categories'];
        array_unshift($categories, ['id' => 0, 'name' => '顶级分类', 'parent_id' => 0]);
        $goods_categories = json_encode($categories);
        $this->assign('goods_categories', $goods_categories);
        $this->assign('brands', $goods_arr['brands']);
        $this->assign('suppliers', $goods_arr['suppliers']);
    }

    public function removeGallery($id)
    {
        if (M('GoodsGallery')->delete($id) === false) {
            $this->error('删除失败');
        } else {
            $this->success('删除成功');
        }
    }

}
